﻿/**************************************************************
 *
 * 唯一标识：0d2b5d70-a489-4f06-9a85-ba209cb8d0b0
 * 命名空间：Sgr.UPMS.Application.DomainEventHandlers
 * 创建时间：2023/9/6 7:43:25
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using MediatR;
using Sgr.Caching.Services;
using Sgr.Domain.Uow;
using Sgr.UPMS.Events;

namespace Sgr.UPMS.Application.DomainEventHandlers
{
    public class UserAuthChangedDomainEventHandle : INotificationHandler<UserAuthChangedDomainEvent>
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly ICacheManager _cacheManager;

        public UserAuthChangedDomainEventHandle(
             IUnitOfWorkManager unitOfWorkManager,
             ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task Handle(UserAuthChangedDomainEvent notification, CancellationToken cancellationToken)
        {
            //清理用户认证缓存
            Task clearCacheAsync()
            {
                return _cacheManager.RemoveAsync(CacheKeys.GetUserPermissionKey(notification.OrgId, notification.UserId), cancellationToken);
            }

            if (_unitOfWorkManager.Current != null && !_unitOfWorkManager.Current.IsCompleted)
                _unitOfWorkManager.Current.AddCompletedHandler(clearCacheAsync);
            else
                await clearCacheAsync();
        }
    }
}